import { reqAddOrUpdateShopCart ,reqCartList,reqCheckCart,reqDeleteCart} from '@/api/shopCart/index'
import { getUUID } from '@/utils/uuid_token'

const state = {
  cartList:[],
  uuid_token: getUUID()
};
const mutations = {
  GETCARTLIST(state,cartList){
    state.cartList = cartList
  }
};
const actions = {
  // 通知服务器添加购物车成功 || 成功之后还可以修改数量 ==》参数解构
  async addOrUpdateShopCart({commit},{ skuId,skuNum }){
    let res = await reqAddOrUpdateShopCart(skuId,skuNum)
    if(res.code == 200){
      return 'ok'
    }else{
      Promise.reject(new Error('fail'))
    }
  },
  //获取购物车列表数据
  async getCartList({ commit }) {
    let result = await reqCartList();
    if (result.code == 200) {
      commit("GETCARTLIST", result.data);
    }
  },
  // 切换商品选中状态
  async checkCartStute({commit},{skuID,isChecked}){
    let res = await reqCheckCart(skuID,isChecked)
    if(res.code == 200){
      return 'ok'
    }else{
      Promise.reject(new Error('fail'))
    }
  },
  // 切换全选状态
  allCheckData({dispatch,state},isChecked){
    let promiseAll = []
    state.cartList[0].cartInfoList.forEach(item=>{
      let promise = dispatch('checkCartStute',{skuID:item.skuId,isChecked})
      promiseAll.push(promise)
    })
    return Promise.all(promiseAll)
  },
  // 删除 一个
  async deleteCart({commit},skuId){
    let res = await reqDeleteCart(skuId)
    if(res.code == 200){
      return 'ok'
    }else{
      Promise.reject(new Error('fail'))
    }
  },
  // 删除多个
  delAllData({dispatch,getters}){
    let promiseAll = []
    getters.cartList.cartInfoList.forEach(element => {
      let promise = element.isChecked == 1 ? dispatch('deleteCart',element.skuId):''
      promiseAll.push(promise)
    });
    return Promise.all(promiseAll)
  },
  
};
const getters = {
  cartList(state) {
    return state.cartList[0] || {};
  }
};
export default {
  state,
  mutations,
  actions,
  getters
}